package com.adnaan.framework.mybatis;

import com.adnaan.framework.security.SecurityUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus自动填充处理器
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("自动填充[INSERT]...");
        
        // 创建时间
        if (metaObject.hasSetter("createTime")) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        }
        
        // 创建人
        if (metaObject.hasSetter("createBy")) {
            this.strictInsertFill(metaObject, "createBy", () -> getUsername(), String.class);
        }
        
        // 更新时间
        if (metaObject.hasSetter("updateTime")) {
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        }
        
        // 更新人
        if (metaObject.hasSetter("updateBy")) {
            this.strictInsertFill(metaObject, "updateBy", () -> getUsername(), String.class);
        }
        
        // 删除标志
        if (metaObject.hasSetter("deleted")) {
            this.strictInsertFill(metaObject, "deleted", () -> "0", String.class);
        }
    }
    
    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("自动填充[UPDATE]...");
        
        // 更新时间
        if (metaObject.hasSetter("updateTime")) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        }
        
        // 更新人
        if (metaObject.hasSetter("updateBy")) {
            this.strictUpdateFill(metaObject, "updateBy", () -> getUsername(), String.class);
        }
    }
    
    /**
     * 获取登录用户名
     */
    private String getUsername() {
        try {
            return SecurityUtils.getUsername();
        } catch (Exception e) {
            return "system";
        }
    }
} 